const router = require('koa-router')()
const mysql = require('mysql')

function __connection() {
	var connection = mysql.createConnection({
		host: 'localhost',
		user: 'root',
		password: 'Gxx@5678',
		database: 'user'
	});
	connection.connect();
	return connection;
}

const query = function (sql, parmas = null) {
	//1.获取数据库连接对象
	var connection = __connection();
	return new Promise(function (resolve, reject) {
		//2执行sql语句
		connection.query(sql, parmas, function (error, results, fields) {
			if (error) throw error;
			resolve(results);
		});
		//3关闭连接
		connection.end();
	})
}
//登录
router.post('/login', async (ctx, next) => {
	const { username, password } = ctx.request.body
	console.log(username, password)
	const data = await query('select * from user');
	let result = data.find(item => item.username === username)
	console.log(result)
	if (result) {
		if (result.password === password) {
			ctx.body = (JSON.stringify({
				code: "01",
				msg: "登录成功",
				Info: result
			}))
		} else {
			ctx.body = (JSON.stringify({
				code: "02",
				msg: "密码错误"
			}))
		}
	} else {
		ctx.body = (JSON.stringify({
			code: "03",
			msg: "账户不存在"
		}))
	}
})
//会员管理
//查
router.get('/vipshop', async (ctx, next) => {
	const data = await query('select * from vip');
	console.log(data)
	ctx.body = data
})
//增
router.post('/vipadd', async (ctx, next) => {
	console.log(ctx.request.body)
	const { serialNumber, mid, name, MemType, discount, Monetary, integrate, storedMoney, tel } = ctx.request.body
	const data = await query(`insert into vip(serialNumber,mid, name, MemType, discount, Monetary, integrate, storedMoney, tel) values (${serialNumber},${mid},'${name}','${MemType}',${discount},${Monetary},${integrate},${storedMoney},${tel})`);
	console.log(data, '|data')
	ctx.body = data
})
//删
router.post('/vipdel', async (ctx, next) => {
	console.log(ctx.request.body)
	const { mid } = ctx.request.body
	await query(`delete from vip  where mid='${mid}';`);
	const data2 = await query('select * from vip')
	ctx.body = data2
})
//改
router.post('/vipfix', async (ctx, next) => {
	console.log(ctx.request.body)
	const { serialNumber, mid, name, MemType, discount, Monetary, integrate, storedMoney, tel } = ctx.request.body
	await query(`update vip set name='${name}'  where serialNumber=${serialNumber}`)
	await query(`update vip set MemType='${MemType}'  where serialNumber=${serialNumber}`)
	await query(`update vip set discount=${discount}  where serialNumber=${serialNumber}`)
	await query(`update vip set Monetary=${Monetary}  where serialNumber=${serialNumber}`)
	await query(`update vip set integrate=${integrate}  where serialNumber=${serialNumber}`)
	await query(`update vip set storedMoney=${storedMoney}  where serialNumber=${serialNumber}`)
	await query(`update vip set tel=${tel}  where serialNumber=${serialNumber}`)
	const data3 = await query('select * from vip')
	ctx.body = data3
})

module.exports = router
